#include <sys/time.h>
#include <time.h>
#include <stdio.h>
#include <stdlib.h>
#include "log.h"


int log_level = LOG_LEVEL_INFO;

/* 设置日志级别,  默认为LOG_LEVEL_WARN */
void log_set_level(int level)
{
	if (level >= LOG_LEVEL_DEBUG && level <= LOG_LEVEL_FATAL)
		log_level = level;
}


static const char *level_str(int level)
{
	switch (level) {
		case LOG_LEVEL_DEBUG:
			return "DBG";
		case LOG_LEVEL_INFO:
			return "INF";
		case LOG_LEVEL_WARN:
			return "WAR";
		case LOG_LEVEL_ERR:
			return "ERR";
		case LOG_LEVEL_FATAL:
			return "FTL";
		default:
			return "XXX";
	}
}

int log_msg(int level, const char *file, int line, const char *fmt, ...)
{
	if (level < log_level) return 0;

	time_t t;	
	struct tm tm;	
	struct timeval tv;
	char fmt_str[128] = {0};
	va_list ap;
	
	gettimeofday(&tv, NULL);
	t = tv.tv_sec;
	localtime_r(&t, &tm);
#if 0
	printf("%02d:%02d:%02d.%03ld %s:%05d [%s] " fmt "",
		tm.tm_hour, tm.tm_min, tm.tm_sec, tv.tv_usec/1000, file, line, level_str(level), ##__VA_ARGS__);
#else
	snprintf(fmt_str, sizeof(fmt_str), "%02d:%02d:%02d.%03ld %s:%05d [%s] %s",
		tm.tm_hour, tm.tm_min, tm.tm_sec, tv.tv_usec/1000, file, line, level_str(level), fmt);

	va_start(ap, fmt);
	vprintf(fmt_str, ap);
	va_end(ap);
#endif

	return 1;
}
